var express = require('express');
var router = express.Router();
var mongdb = require('mongodb');
var MongoClient = require('mongodb').MongoClient
var config = require('../config/db')
var passport = require('passport')
const jwt = require('jsonwebtoken')
/*添加订单 */
router.post('/Addorders', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
  //获取需要添加的订单商品信息
  let order = req.body.order
  console.log('myorder: ', order);
  //获取数据库连接对象
  let client = await MongoClient.connect(config.url)
  let db = client.db()
  //创建订单对象
  let newOrder = {
    "userId": req.user._id,
    "products": order.product,
    "totalPrice": order.totalprice,
    "addTime ": new Date(),
    "state": 0,      //0-待支付，1-已支付
    "comment": null
  }
  //执行添加订单的操作
  let results = await db.collection('orderTest').insertOne(newOrder)
  //判断是否添加成功
  if (results.acknowledged) {
    let orders = await db.collection('orderTest').find({ userId: req.user._id }).sort({ 'addTime': -1 }).toArray()
    console.log('orders', orders[0]._id)
    res.json({ code: 200, message: 'ok', data: orders[0]._id });
  } else {
    res.json({ code: 200, message: 'error' });
  }
});

/*支付，确认和评论，并修改订单状态*/
router.put('/editOrder', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
  //获取需要修改的订单商品信息
  let orderId = req.body.params.orderId
  //获取数据库连接对象
  let client = await MongoClient.connect(config.url)
  let state = req.body.params.state
  let db = client.db()
  console.log('orderId:', orderId);
  let results = await db.collection('orderTest').updateOne({ _id: new mongdb.ObjectId(orderId) }, { $set: { state:1 } })
  //判断是否修改成功
  if (results.acknowledged) {
    console.log('results: ', results)
    res.json({ code: 200, message: 'ok' });
  } else {
    res.json({ code: 280, message: 'error' });
  }
});


router.get('/Getorder', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
  let client = await MongoClient.connect(config.url)
  let db = client.db()
  let orders = await db.collection('orderTest').find({ userId: req.user._id }).sort({ 'addTime': -1 }).toArray()
  if (orders.length >= 0) {
    res.json({ code: 200, message: 'ok', data: orders });
  } else {
    res.json({ code: 200, message: 'error' });
  }
});
module.exports = router;
